import { lazyReportBatch } from '../report.js';

export const originalProto = XMLHttpRequest.prototype;
export const originalSend = originalProto.send;
export const originalOpen = originalProto.open;
// 重写是为了拿到监测数据上报
function overwriteOpenAndSend() {
    originalProto.open = function newOpen(...args) {
        this.url = args[1];
        this.method = args[0];
        originalOpen.apply(this, args);

    }
    originalProto.send = function newSend(...args) {
        this.startTime = Date.now();
        const onLoaded  = () => {
            this.endTime = Date.now();
            this.duration = this.endTime - this.startTime;
            const {url,method,startTime,endTime,duration,status} = this;
            const reportData = {
                type:"performance",
                subType:"xhr",
                url,
                method:method.toUpperCase(),
                startTime,
                endTime,
                duration,
                status,
                success:status >= 200 && status < 300,
            }
            // TODO:上报数据
            lazyReportBatch(reportData);
            this.removeEventListener('loadend',onLoaded,true);
        }
        // loadend 事件总是在一个资源的加载进度停止之后被触发
        this.addEventListener('loadend',onLoaded,true);//捕获时
        originalSend.apply(this, args);
    }
}
export default function xhr() {
    overwriteOpenAndSend();

}
